<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>06_列表渲染_过滤与排序</title>
</head>
<body>
<!--
1. 列表过滤
2. 列表排序
-->

<div id="demo">
    <input v-model="searchName"/><br/>
    <ul>
        <li v-for="(p,index) in filterPersons" :key="index">
            {{index}}--{{p.name}}---{{p.age}}
        </li>
    </ul>
    <button @click="orderType=2">年龄升序</button>
    <button @click="orderType=1">年龄降序</button>
    <button @click="orderType=0">原本顺序</button>

</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: "#demo",
        data: {
            searchName: '',
            orderType: 0, // 0代表不排序, 1代表降序, 2代表升序
            persons: [
                {name: 'Tom', age: 18},
                {name: 'Jack', age: 17},
                {name: 'Bob', age: 19},
                {name: 'Mary', age: 16}
            ],
        },
        computed: {
            filterPersons() {
                const {searchName, persons, orderType} = this;

                let returnResult = null;
                // 如果searchName 为空就不过滤
                if (searchName === '') {
                    returnResult = [...persons];
                }
                // 过滤
                returnResult = persons.filter(p => p.name.indexOf(searchName) !== -1);

                // 判断是否需要排序
                switch (orderType) {
                    case 2:
                        returnResult = returnResult.sort((val1, val2) => val1.age - val2.age);
                        break;
                    case 1:
                        returnResult = returnResult.sort((val1, val2) => val2.age - val1.age);
                        break;
                }
                return returnResult;
            }
        }
    })
</script>
</body>
</html>